﻿using HomeCareLibrary.AppService;
using HomeCareLibrary.Constants;
using HomeCareLibrary.Filters;
using HomeCareLibrary.Helpers;
using HomeCareLibrary.Models;
using System;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Linq;

namespace HomeCareLibrary.Controllers
{
    /// <summary>
    /// Base controller implementation which provides the sponsor code checking, cooking/LSO checking logic.
    /// </summary>
    [CheckSponsor]
    public abstract class BaseController : Controller
    {
        #region "Overridden Methods"
        
        /// <summary>
        /// Called before the action method is invoked.
        /// </summary>
        /// <param name="filterContext">Information about the current request and action.</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (ConfigurationManager.AppSettings["EnableBaseControlling"] == "true")
            {
                var session = filterContext.RequestContext.HttpContext.Session;


                //(28.1.2014)  :Only for Testing . we are making cookie blank if mode= IPHONE_APP OR mode= ANDROID_APP
                var modePostedForTesting = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.MODE);
                if (modePostedForTesting != null)
                {
                    var modeTesting = modePostedForTesting.AttemptedValue;

                    if (modeTesting == ApplicationModeConstants.IPHONE_APP || modeTesting == ApplicationModeConstants.ANDROID_APP)
                    {
                        //comment on(5.2.2014)
                        //HttpCookie expireCookie = new HttpCookie(CookieConstants.HOME_CARE_LOGON_COOKIE.ToString());
                        //expireCookie.Expires = DateTime.Now.AddYears(1);
                        //Response.Cookies.Add(expireCookie);
                    }
                    else
                    {
                        //comment on(5.2.2014)
                        // Cookie exists but new session
                        //if (Request.IsAuthenticated)
                        //{
                        //    if (Session[SessionConstants.USER_ID] == null)
                        //    {
                                
                        //        var cookieData = HttpContext.User.Identity.Name;
                        //        var splitData = cookieData.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        //        if (splitData.Length > 0)
                        //        {
                        //            session[SessionConstants.USER_ID] = splitData[0].Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries).Last();
                        //            session[SessionConstants.USER_NAME] = splitData[1].Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries).Last();
                        //            var promoCodeSplit = splitData[2].Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                        //            if (promoCodeSplit != null && promoCodeSplit.Length > 1)
                        //            {
                        //                session[SessionConstants.PROMO_CODE] = promoCodeSplit.Last();
                        //            }
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    // Guest User
                        //    session[SessionConstants.USER_ID] = "-1";
                        //}
                    }
                }

                // fetch the POST data values
                var userIdPosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.USER_ID);
                var modePosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.MODE);
                var userNamePosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.USER_NAME);
                var passwordPosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.PASSWORD);
                var promoCodePosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.PROMO_CODE);
                var activityTypePosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.ACTIVITY_TYPE);
                var homeNumberPosted = filterContext.Controller.ValueProvider.GetValue(PostDataNameConstants.Home_Number);

                if (homeNumberPosted != null)
                {
                    var homeNumber = homeNumberPosted.AttemptedValue;
                    if (!String.IsNullOrEmpty(homeNumber))
                    {
                        session[SessionConstants.HOME_NUMBER] = homeNumber;
                    }
                }
                //session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP;
                //this line we add here for (/terms of use-that not need userId)
                if (modePosted != null)
                {
                    session[SessionConstants.MODE] = modePosted.AttemptedValue;
                }
                if (userIdPosted != null && modePosted != null)// && userNamePosted != null && passwordPosted != null && promoCodePosted != null)
                {
                    if (!string.IsNullOrEmpty(userIdPosted.AttemptedValue))
                    {
                        var userId = userIdPosted.AttemptedValue;
                        var userName = userNamePosted != null ? userNamePosted.AttemptedValue : string.Empty;
                        var mode = modePosted.AttemptedValue;
                        var promoCode = promoCodePosted != null ? promoCodePosted.AttemptedValue : string.Empty;
                        var activityType = activityTypePosted != null ? activityTypePosted.AttemptedValue : string.Empty;
                       
                        // if the mode is from mobile, check if user exists in DB and if valid, update the session variables.
                        if (mode == ApplicationModeConstants.IPHONE_APP || mode == ApplicationModeConstants.IPAD_APP || mode == ApplicationModeConstants.ANDROID_APP && !string.IsNullOrEmpty(userId))
                        {
                            int userIdDecrypted = 0;

                            // Check for decrypted userid being a valid user, if yes; updated Session.
                            if (int.TryParse(userId.DecryptData(), out userIdDecrypted))
                            {
                                if (userIdDecrypted > 0)
                                {
                                    //(28.1.2014):if session is already set, then don't need to do userId validation again
                                    if (session[SessionConstants.USER_ID] == null || int.Parse(session[SessionConstants.USER_ID].ToString()) != userIdDecrypted)
                                    {
                                        //check user exist
                                        UserAppService service = new UserAppService();
                                        var user = service.FindUser(userIdDecrypted);
                                        if (string.IsNullOrEmpty(promoCode))
                                        {
                                            promoCode = user.sponsor;
                                            
                                        }
                                        if (mode == ApplicationModeConstants.IPHONE_APP || mode == ApplicationModeConstants.IPAD_APP || mode == ApplicationModeConstants.ANDROID_APP)
                                        {
                                            session[SessionConstants.PROMO_CODE] = promoCode;
                                        }
                                        if (user != null)
                                        {
                                            //update session userid
                                            session[SessionConstants.USER_ID] = user.user_id1.ToString();

                                            //(28.1.2014)check userId, and if valid, set session variables (userId, userName, password, promoCode, mode=androidApp)
                                            session[SessionConstants.USER_NAME] = user.user_name.ToString();
                                            session[SessionConstants.PASSWORD] = user.password.ToString();
                                            session[SessionConstants.MODE] = mode;

                                            if (!string.IsNullOrEmpty(activityType))
                                            {
                                                session[SessionConstants.ACTIVITY_TYPE] = activityType;
                                            }

                                           

                                            //session promocode is set by CheckSponsorAttribte.cs

                                            // Update cookie to set the user as authenticated
                                            //var authTicket = new FormsAuthenticationTicket(1, user.user_id1.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), false, user.user_name);
                                            //string cookieContents = FormsAuthentication.Encrypt(authTicket);

                                            //var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                                            //{
                                            //    Expires = authTicket.Expiration,
                                            //    Path = FormsAuthentication.FormsCookiePath
                                            //};

                                            //filterContext.HttpContext.Response.Cookies.Add(cookie);
                                        }
                                        else
                                        {
                                            //(28.1.2014): If user is not valid , we are clearing the session.
                                            //session.Clear();
                                            //session.Abandon();
                                            //session.RemoveAll();

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }

        #endregion

        #region "Protected Properties"
        
        /// <summary>
        /// Gets or sets the sponsor code.
        /// </summary>
        /// <value>
        /// The _ sponsor code.
        /// </value>
        protected string _SponsorCode
        {
            get;
            set;
        } 

        #endregion

    }
}
